﻿var background = chrome.extension.getBackgroundPage();
var sites = background.exports.work.sites;
var jiathis_config = {
    url: "",
    title: ""
};
function loadWatchlist(jqdiv, noticeType){
    var ul = $('<table class="table table-bordered table-striped table-condensed tablesorter">');
    ul.append(getHeader());
    var tbody = $('<tbody>');
    for (var k in sites){
        for (var f in sites[k]) {
                tbody.append(
                    getLi(k, f, sites[k][f], 'trackItemTmpl')
                );
        }
    }
    ul.append(tbody);
    jqdiv.append(ul);

    function getHeader() {
        var thead = $('<thead>');
        var tr = $('<tr>');
        tr.append($('<th>').css('width', '100px').html('关注度'));
        tr.append($('<th>').html('网站'));
        tr.append($('<th>').html('商品名称').css('width', '180px'));
        tr.append($('<th>').html('关注时间'));
        tr.append($('<th>').html('关注价格'));
        tr.append($('<th>').html('降价'));
        tr.append($('<th>').html('当前价格'));
        tr.append($('<th>').html('库存').css('display', 'none'));
        tr.append($('<th>').html('赠券').css('width', '80px'));
        tr.append($('<th>').html('赠品').css('width', '80px'));
        tr.append($('<th>').html('评价').css('display', 'none'));
        tr.append($('<th>'));
        thead.append(tr);
        
        return $('<div>').append(thead).html();
    }
}

function loadWaterfallData(jqdiv) {
    for (var k in sites) {
        for (var f in sites[k]) {
            jqdiv.append(
                    getLi(k, f, sites[k][f], 'trackItemWaterfall')
                );
        }
    }
}

function getLi(confKey, url, urlValues, templateId) {
    var tmpl = $.template(null, 'http://click.union.360buy.com/JdClick/?unionId=5990&t=4&to=${url}');
    var unionUrl = $.tmpl(tmpl, { 'url': url }).text();
    var gift = [];
    $(urlValues.gift).each(function () {
        $(this).find('a:eq(0)').attr('title', $(this).find('a:eq(1)').text())
            .attr('href', $.tmpl(tmpl, { 'url': $(this).find('a:eq(1)').attr('href') }).text());
        gift.push($('<div>').append($(this).find('a:eq(0)')).html());
    });

    var hasTwoMorePrice = urlValues.price && urlValues.price.length > 1;
    var reduct = 0, quatity = '', percent = '';
    if (hasTwoMorePrice) {
        reduct = urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1];
        quatity = reduct > 0 ? reduct : '';

        percent = quatity != '' ? Math.round((reduct / urlValues.price[urlValues.price.length - 1][1]) * 100) + ' %' : '';
    }
    var trackItem = {
        site: confKey,
        url: url,
        name: urlValues.name.trim(),
        date: urlValues && urlValues.price && urlValues.price[0] ? formatDate(new Date(urlValues.price[0][0]), 'MM/d/yyyy') : '',
        price: urlValues && urlValues.price && urlValues.price[0] ? urlValues.price[0][1] : '',
        reduction: {
            //                quatity: urlValues.price && urlValues.price.length > 1 && urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1] > 0 ? urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1] : '',
            //                percent: urlValues.price && urlValues.price.length > 1 && urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1] > 0 ? '('+ (Math.round(urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1] / urlValues.price[0][1]) * 100) + '%）' : ''
            //                quatity: urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1],
            //                percent: Math.round(((urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1]) / urlValues.price[0][1]) * 100) + '%'
            percent: percent,
            quatity: quatity,
            quatityText: quatity > 0 ? ('降价：' + quatity) : ''
        },
        curprice: urlValues && urlValues.price.length >= 1 && urlValues.price[urlValues.price.length - 1] ? urlValues.price[urlValues.price.length - 1][1] : '',
        coupon: $(urlValues.coupon).text().trim().length > 0 ? '有' : '',
        gift: $(urlValues.gift).text().trim().length > 0 ? '有' : '', //gift.join(''),
        stock: urlValues.stock,
        reviews: {}, //$.extend({ goodPercent: Math.round(urlValues.reviews.good / urlValues.reviews.total * 100) }, urlValues.reviews),
        buyUrl: urlValues.buyUrl,
        imgUrl: urlValues.imgUrl,
        unionUrl: unionUrl,
        bought: urlValues.bought == 'checked' ? '<label style="display:inline;padding-left:10px"><input type="checkbox" style="display:inline" checked name="bought" /><span>已购</span></label>' : '<label style="display:inline;padding-left:10px"><input style="display:inline" type="checkbox" name="bought" /><span>未购</span></label>'
    };
    return $("#" + templateId).tmpl(trackItem);
}

function getWaterfallBlock(confKey, url, urlValues) {
    var tmpl = $.template(null, 'http://click.union.360buy.com/JdClick/?unionId=5990&t=4&to=${url}');
    var unionUrl = $.tmpl(tmpl, { 'url': url }).text();
    var gift = [];
    $(urlValues.gift).each(function () {
        $(this).find('a:eq(0)').attr('title', $(this).find('a:eq(1)').text())
            .attr('href', $.tmpl(tmpl, { 'url': $(this).find('a:eq(1)').attr('href') }).text());
        gift.push($('<div>').append($(this).find('a:eq(0)')).html());
    });

    var hasTwoMorePrice = urlValues.price && urlValues.price.length > 1;
    var reduct = 0, quatity = '', percent = '';
    if (hasTwoMorePrice) {
        reduct = urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1];
        quatity = reduct > 0 ? reduct : '';

        percent = quatity != '' ? Math.round((reduct / urlValues.price[urlValues.price.length - 1][1]) * 100) + ' %' : '';
    }
    var trackItem = {
        site: confKey,
        url: url,
        name: urlValues.name,
        date: urlValues && urlValues.price && urlValues.price[0] ? formatDate(new Date(urlValues.price[0][0]), 'MM/d/yyyy') : '',
        price: urlValues && urlValues.price && urlValues.price[0] ? urlValues.price[0][1] : '',
        reduction: {
            //                quatity: urlValues.price && urlValues.price.length > 1 && urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1] > 0 ? urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1] : '',
            //                percent: urlValues.price && urlValues.price.length > 1 && urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1] > 0 ? '('+ (Math.round(urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1] / urlValues.price[0][1]) * 100) + '%）' : ''
            //                quatity: urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1],
            //                percent: Math.round(((urlValues.price[0][1] - urlValues.price[urlValues.price.length - 1][1]) / urlValues.price[0][1]) * 100) + '%'
            percent: percent,
            quatity: quatity
        },
        curprice: urlValues && urlValues.price.length >= 1 && urlValues.price[urlValues.price.length - 1] ? urlValues.price[urlValues.price.length - 1][1] : '',
        coupon: $(urlValues.coupon).text().trim().length > 0 ? '有' : '',
        gift: $(urlValues.gift).text().trim().length > 0 ? '有' : '', //gift.join(''),
        stock: urlValues.stock,
        reviews: {}, //$.extend({ goodPercent: Math.round(urlValues.reviews.good / urlValues.reviews.total * 100) }, urlValues.reviews),
        buyUrl: urlValues.buyUrl,
        imgUrl: urlValues.imgUrl,
        unionUrl: unionUrl
    };
    return $("#trackItemTmpl").tmpl(trackItem);
}

function needsToShow(noticeType, site, url, details)
{
    var result = false;
    if(noticeType && noticeType.length > 0)
    {
        var types = noticeType.split(',');
        console.log(noticeType);
        $.each(types, function(k, v){
            if ($.trim(v).length > 0
            && details.noticeSettings 
            && details.noticeSettings[v] && $.trim(details.noticeSettings[v].enabled) == 'checked')
            {
                result = true;
                return false;
            }
        });
    }

    return result;
}

function setShare(title, url) {
    jiathis_config.title = title;
    jiathis_config.url = url;
}

function bindEvents() {
    $(':button[c="del"]').click(function () {
        var yes = confirm('将删除与此页面相关的数据');
        var btn = this;
        if (yes) {
            $.when((function () {
                var site = $(getRowTDs(btn)[1]).text().trim();
                var url = $(getRowTDs(btn)[2]).find('a').attr('href').trim();
                background.exports.work.delUrl(site, url);
                $(btn).parentsUntil('tbody').remove();
                //location.reload();
            })()).done(function () {
                displayMessage('删除成功');
            });
        }
    });

    $('*[c=share]').mouseover(function () {
        var tds = getRowTDs(this);
        var title = [];
        title.push("我在");
        title.push($(tds[1]).text().trim());
        title.push("发现了一个非常不错的商品：");
        title.push($(tds[2]).text().trim());
        title.push("报价：");
        title.push($(tds[6]).text().trim());
        title.push("。 感觉不错，分享一下");
        //title.push($(tds[2]).find('a').attr('href').trim());

        var url = $(tds[2]).find('a').attr('href');
        var tmpl = $.template(null, 'http://click.union.360buy.com/JdClick/?unionId=5990&t=4&to=${url}');
        var unionUrl = $.tmpl(tmpl, { 'url': url }).text();

        setShare(title.join(''), unionUrl);
    });

    //$('a[c=setNotice]').click(function () {
    $('div[c=rank]').stars({
        inputType: "select",
        split: 1,
        callback: function (ui, type, value) {
            var sites = background.exports.work.sites;
            var tds = getRowTDs(ui.element);
            var site = $(tds[1]).text().trim();
            var url = $(tds[2]).children('a').attr('href').trim();
            sites[site][url].rank = value;
            background.exports.work.save();

            $('#watchlist>table')
            .trigger("update")
            .trigger("appendCache");
        }
    }).each(function () {
        var sites = background.exports.work.sites;
        var tds = getRowTDs(this);
        var site = $(tds[1]).text().trim();
        var url = $(tds[2]).children('a').attr('href').trim();
        var value = sites[site][url].rank;

        $(this).stars('select', value).stars({
            captionEl: $(this).prev('div').find('span[c=rankvalue]')
        });
    });

        // Initialise filter Plugin
        //demo: view-source:http://www.picnet.com.au/resources/tablefilter/demo.htm
    var options1 = {
        additionalFilterTriggers: [$('#ckbReduction'), $('#ckbReduction'), $('#ckbStock'), $('#ckbCoupon'), $('#ckbGift')],
        clearFiltersControls: [$('#ckbAll')],
        matchingRow: function (state, tr, textTokens) {
            if (!state || !state.id) { return true; }

            if (state.value) {
                $('#ckbAll').attr('checked', false);
            }
            else {
                $('#ckbAll').attr('checked', true);
            }
            var site = tr.children('td:eq(1)').text().trim();
            var url = tr.children('td:eq(2)').find('a:eq(0)').attr('href').trim();
            var reduction = tr.children('td:eq(5)').text();
            var stock = tr.children('td:eq(7)').text();
            var coupon = tr.children('td:eq(8)').text();
            var gift = tr.children('td:eq(9)').text();
            if (!site || !url) return true;
            var noticeSettings = sites[site][url].noticeSettings;
            switch (state.id) {
                case 'ckbReduction': return state.value !== true || reduction.trim().length > 0;
                case 'ckbStock': return state.value !== true || stock.indexOf('现货') > -1;
                case 'ckbCoupon': return state.value !== true || coupon.trim().length > 0;
                case 'ckbGift': return state.value !== true || gift.trim().length > 0;
                default: return true;
            }
        },
        enableCookies: false
    };

    $('#watchlist').tableFilter(options1);
    $('#watchlist').find('tr.filters').remove(); //删掉tableFilter的filter行
    $('#ckbAll').attr('checked', true);

    $('div[c=notice] input[type=button]').live('click', function () {
        $.when((function () {
            var set = {
                coupon: { enabled: $(event.target).parentsUntil('form').find(':checkbox[name=coupon]').is(':checked') ? 'checked' : '', param: '' },
                cheapest: { enabled: $(event.target).parentsUntil('form').find(':checkbox[name=cheapest]').is(':checked') ? 'checked' : '', param: '' },
                reduction: { enabled: $(event.target).parentsUntil('form').find(':checkbox[name=reduction]').is(':checked') ? 'checked' : '', param: $(event.target).parentsUntil('form').find('input[name=reductionTo]').val() },
                onSale: { enabled: $(event.target).parentsUntil('form').find(':checkbox[name=onSale]').is(':checked') ? 'checked' : '', param: $(event.target).parentsUntil('form').find('input[name=onSalePercent]').val() },
                notes: $(event.target).parentsUntil('form').find('*[name=notes]').val()
            };

            var tds = getRowTDs(event.target);
            var site = $(tds[1]).text().trim();
            var url = $(tds[2]).children('a:eq(0)').attr('href');
            sites[site][url].noticeSettings = set;
            background.exports.work.save();
        })())
        .done(function () {
            displayMessage('保存成功');
        })
        .fail(function () {
            displayMessage('保存失败');
        })
    });
}

function bindWaterfallEvents() {
    $(':button[c=waterfalldel]').click(function () {
        var yes = confirm('将删除与此页面相关的数据');
        var btn = this;
        if (yes) {
            $.when((function () {
                var site = '360buy.com';//TODO
                var url = $(btn).prev('a').attr('href').trim();
                background.exports.work.delUrl(site, url);
                $(btn).parentsUntil('#waterfall').remove();
                location.reload();
            })()).done(function () {
                displayMessage('删除成功');
            });
        }
    });

    $(':checkbox[name=bought]').live('click', function () {

        var btn = this;
        $.when((function () {
            var site = '360buy.com'; //TODO
            var url = $(btn).parent().prevUntil('a').prev().attr('href');

            sites[site][url].bought = $(btn).attr('checked');
            background.exports.work.save();
        })()).done(function () {
            $(btn).next('span').html($(btn).attr('checked') ? '已购' : '未购');
            displayMessage('保存成功');
        });
    });
}


function setNotice()
{
$('a[c=setNotice]').each(function(k,v){
    var tds = getRowTDs(this);
    var site = $(tds[1]).text().trim();
    var url = $(tds[2]).children('a').attr('href').trim();

    var sites = background.exports.work.sites;
    var noticeSettings = sites[site][url].noticeSettings;
    var set;
    if (!noticeSettings) {
        noticeSettings = {
            coupon: { enabled: '', param: '' },
            cheapest: { enabled: '', param: '' },
            reduction: { enabled: '', param: '' },
            onSale: { enbled: '', param: '' }
        };
    }

    var html = $('#noticeSettingTmpl').tmpl(noticeSettings);

    if ($(this).next().find(':checkbox').length == 0) {
        $(this).after(html);
    }

    $('div[c="notice"]>:button:eq(1)').on('click', function () {
        $('div[c="notice"]').parent().hide();
    });
//});
});
}

function getRowTDs(td) {
    return $(td).parentsUntil('table').children('td');
}

function setSort()
{
    var myTextExtraction = function(node)  
    {  
        var text = '';
        // extract data from markup and return it  
        if(node && $(node).find('div[c=rank] :hidden[name=selrate]').length)
        {
            text = $(node).find('div[c=rank] :hidden[name=selrate]').val();
        }
        else
        {
            text = $(node).text();
        }

        return text;
    }

    $('#watchlist>table').tablesorter({
        sortList: [[0,1]],
        headers: { 
                0: { 
                    sorter:'star'
                },
                7: {
                    // disable it by setting the property sorter to false 
                    sorter: false
                },
                8: {
                    // disable it by setting the property sorter to false 
                    sorter: false
                },
                9: {
                    // disable it by setting the property sorter to false 
                    sorter: false
                }, 
                10: { 
                // disable it by setting the property sorter to false 
                sorter: false 
                }, 
                11: { 
                    // disable it by setting the property sorter to false 
                    sorter: false 
                }
            },
        textExtraction: myTextExtraction
    });
}

function displayMessage(msg) {
    $('<div class="messageInfo">' + msg + '</div>').appendTo('#msgInfoWrap').fadeIn('slow').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function () {
        $(this).remove();
    });
}

function loadList() {
    var div = $('#watchlist');
    loadWatchlist(div);
    bindEvents();
    setNotice();
    setSort();
}

function loadWaterfallList() {
    var div = $('#waterfall');
    $.when((function () {
        loadWaterfallData(div);
    })()).done(function () {
        bindWaterfallEvents();
        var width = ($('body').width() / 5) - 30;
        $('img.item').css('width', width + 'px').css('height', width + 'px');

        //        div.waterfall({
        //            itemSelector: '.waterfallblock',
        //            columnCount: 5,
        //            columnWidth: $('body').width() / 5,
        //            isResizable: false,
        //            isAnimated: false,
        //            Duration: 500,
        //            Easing: "swing",
        //            endFn: function () { }
        //        });

        //        $('#waterfall .waterfallblock').wookmark({ offset: 2 });

        //        window.onresize = function (event) {
        //            $('#waterfall .waterfallblock').wookmark({ offset: 2 });
        //        }
        //        $('#waterfall').masonry({
        //            itemSelector: '.waterfallblock',
        //            columnWidth: 252
        //        });

//        var count = $('#waterfall .waterfallblock').length;
//        if (count) {
//            for (var i = 0; i < 5 - count % 5; i++) {
//                var paddingDiv = $('<div>').attr('class', 'waterfallblock clearfix').height('309px');
//                $('#waterfall').append(paddingDiv);
//            }
//        }
    });
}

$(function () {
    loadWaterfallList();

    $(':radio[name=align]').click(function () {
        var view = $(this).val();
        if (view == 'list') {
            $('#list').show();
            loadList();
            $('#waterfall').hide();
        }
        else if (view == 'waterfall') {
            $('#waterfall').show();
            $('#list').hide();
        }
    });
});
